<?php

/**
 * 分包任务类
 */

namespace App\Jobs;

use App\Repository\Main\MainRepository;
use Carbon\Carbon;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class OrderSubmitTest extends Job
{
    protected $type;
    protected $orderNum;
    public $tries = 3;
    public $log = null;
    public $timeout = 300;

    public function __construct($orderNum, $type, $time = 0)
    {
        $this->log = new Logger('OrderSubmitTest');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/TestOrderSubmit.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $this->type = $type;
        $this->orderNum = $orderNum;
        $this->delay($time);  // 多少s后执行
    }

    /**
     * 执行任务
     *
     * @return void
     */
    public function handle()
    {
        ini_set('max_execution_time', 300);
        $model = new MainRepository();
        $where = [
            'ordersno' => $this->orderNum,
        ];
        if (is_array($this->orderNum)) {
            $where = $this->orderNum;
        }
        if ($this->type == 'smsAndPushOrder') {
            $this->log->info('测试:' . $this->type . ' where:' . serialize($where));
        }
        $res = $model->sendOrder($where, $this->type);
        // 通过异步的记录下参数和结果 容易根据某个单号 排查问题
        $this->log->info('类型' . $this->type . '参数' . (is_array($this->orderNum) ? json_encode($this->orderNum) : $this->orderNum) . '返回结果' . json_encode($res));
        //$this->job->delete();
    }

    public function retryUntil()
    {
        //任务超时时间
        $time = 24 * 60 * 60;
        return Carbon::now()->addSeconds($time);
    }

    /**
     * 处理失败任务
     *
     * @return void
     */
    public function failed()
    {
        $this->log->info('提交上游失败操作' . $this->type . '参数' . (is_array($this->orderNum) ? json_encode($this->orderNum) : $this->orderNum));
        $time = 60 * 4;
        $where = [
            'orderno' => $this->orderNum,
        ];
        // 延时多长时间 延长4个小时在重新提交
        if (is_array($this->orderNum)) {

            $where = $this->orderNum;
        }
        // echo 44444444;
        // dispatch(new OrderSubmit($where, $this->type))->delay(Carbon::now()->addMinutes($time));
        // $modelTasking = new WlktaskingRepository();
        // $modelTasking->restore($this->id);
    }
}
